package com.zerdoor.service.impl;

import com.zerdoor.dao.ITaskSigningDao;
import com.zerdoor.service.ICommonPayService;
import com.zerdoor.service.ITaskSigningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhongjieyu on 2014/12/30.
 */
@Service
public class TaskSigningServiceImpl implements ITaskSigningService {

    @Autowired
    private ITaskSigningDao taskSigningDao;

    @Autowired
    private ICommonPayService commonPayService;

    @Override
    public List<Map<String, String>> findContractNameByItemId(int itemId,int user_id,int type) throws Exception {

        Map<String,Object> param = new HashMap<String, Object>();
        param.put("itemId",itemId);
        param.put("user_id",user_id);
        param.put("type",type);


        return taskSigningDao.findContractNameByItemId(param);
    }

    @Override
    public Map<String, Object> findContractByContractId(int contractId) throws Exception {

        Map<String, Object> map = taskSigningDao.findContractByContractId(contractId);

        if(map != null){

            //放入合同条例
            map.put("termsContract",taskSigningDao.findTermsContract());

            //放入阶段
            List<Map<String,Object>> itemStages = taskSigningDao.findItemStageByContractId(contractId);
            for(Map<String,Object> itemStage : itemStages){

                if(125101 == (Integer)itemStage.get("stage")){

                    map.put("itemStage1",itemStage);
                }else if(125102 == (Integer)itemStage.get("stage") ){

                    map.put("itemStage2",itemStage);
                }else if(125103 == (Integer)itemStage.get("stage") ){

                    map.put("itemStage3",itemStage);
                }

            }

            //判断合同对应的项目是否使用0手续费卡，如果不是则放入手续费支付百分比
            if(map.get("use_fee") == null ){
                map.put("use_fee",101002);
            }

            int use_fee = Integer.parseInt(String.valueOf( map.get("use_fee") ));

            //101001 为是
            if(101001 == use_fee){
                //放入手续费百分比值
                map.put("feePer",0);
            }else{

                //查询手续费支付百分比值，6为固定配置表ID
                float feePer = commonPayService.findScaleValue(6);

                //放入手续费百分比值
                map.put("feePer",feePer);

            }

            //判断是否首次推荐人是否首次推广，如果是者查询推广费百分比
            //判断是否为空
            if(map.get("baile_userId") == null){
                map.put("ispo_sender",101002);
            }

            int ispo_sender = taskSigningDao.findUserIspoSenderByPresenter(String.valueOf(map.get("baile_userId")));

            //为是首次推广，查询并放入推广费百分比
            if(101001 == ispo_sender){

                //查询推广费支付百分比值，7为固定配置表ID
                float ProExpensesPer = commonPayService.findScaleValue(7);

                //放入推广费百分比值
                map.put("proExpensesPer",ProExpensesPer);


            }else{
                //放入推广费百分比值
                map.put("proExpensesPer",0);
            }

            //判断是否是计件任务，如果是计件任务，那么查询剩余件数
            if(101001 == Integer.parseInt(String.valueOf(map.get("is_piece")))){

                //得到确认计件数量
                int surePieceNum = taskSigningDao.findSumSurePieceNum(String.valueOf(map.get("item_id")));
                //得到总计件数
                int sumPieceNum = Integer.parseInt(String.valueOf(map.get("sumPieceNum")));
                //放入剩余计件数量
                map.put("surplusPieceNum",sumPieceNum - surePieceNum);
            }
        }


        return map;
    }


    @Override
    public void updateContractByContractId(Map<String, String> param) throws Exception {

        taskSigningDao.updateContractByContractId(param);

        //默认取出第一个阶段检查ID是否为空，如果为空则先清空该合同下的阶段数据，防止阶段重复插入问题
        if("".equals(param.get("stage_id" + 1)) || param.get("stage_id" + 1) == null){

            taskSigningDao.deleteItemStageByContractId(param.get("contract_id"));

        }

        //阶段状态
        boolean flag = false;

        for(int i = 1; i < 4; i ++){

            //如果状态为真那么就表示该阶段已无效
            if(flag){

                //如果id 不为空那么就删除该阶段数据
                if(!"".equals(param.get("stage_id" + i)) && param.get("stage_id" + i) != null){
                    taskSigningDao.deleteItemStageById(param.get("stage_id" + i));
                }

                continue;
            }


            Map<String,String> stage = new HashMap<String, String>();

            stage.put("contract_id",param.get("contract_id"));
            stage.put("stage_id",param.get("stage_id" + i));
            stage.put("scale",param.get("scale" + i));
            stage.put("result_claim",param.get("result_claim" + i));
            stage.put("pay_date",param.get("pay_date" + i));
            stage.put("stage",(125100 + i)  + "");

            //如果阶段ID为空，那么表示该阶段数据不存在，则新增
            if(stage.get("stage_id") == null || "".equals(stage.get("stage_id"))){

                //新增阶段数据
                taskSigningDao.insertItemStage(stage);
            }else{
                //修改阶段定义数据
                taskSigningDao.updateItemStageById(stage);
            }


            //如果金额小于2000那么就不需要再插入其他两个阶段数据
            if(Float.parseFloat(param.get("total_price")) <= 2000 ){
                flag = true;
            }
        }



    }

    @Override
    public void updateBaileSureContractByContractId(int contractId) throws Exception {

        taskSigningDao.updateBaileSureContractByContractId(contractId);
    }

    @Override
    public void updateArtistSureContractByContractId(int contractId) throws Exception {

        //确认
        taskSigningDao.updateArtistSureContractByContractId(contractId);

        //修改任务订单 popur 推广费字段
        //推广费百分比
        float proExpensesPer = 0f;
        //手续费百分比
        float feePer = 0f;

        Map<String, Object> map = taskSigningDao.findContractByContractId(contractId);

        //判断合同对应的项目是否使用0手续费卡，如果不是则放入手续费支付百分比
        if(map.get("use_fee") == null ){
            map.put("use_fee",101002);
        }

        int use_fee = Integer.parseInt(String.valueOf( map.get("use_fee") ));

        //101001 为是
        if(101001 != use_fee){
            //查询手续费支付百分比值，6为固定配置表ID
            feePer = commonPayService.findScaleValue(6);
        }

        //判断是否首次推荐人是否首次推广，如果是者查询推广费百分比

        //查询任务订单
        Map orderTaskMap = taskSigningDao.findOrderTaskByItemId(String.valueOf(map.get("item_id")));
        int ispo_sender = taskSigningDao.findUserIspoSenderByPresenter(String.valueOf(map.get("baile_userId")));


        //为是首次推广，查询并放入推广费百分比
        if(101001 == ispo_sender){

            //存入首次推广状态
            orderTaskMap.put("ispo",101001);
            //改变发包方首次推荐状态
            taskSigningDao.updateUserIspoSenderByPresenter(String.valueOf(map.get("baile_userId")));

        }

        //得到项目是否首次推广状态
        int ispo = Integer.parseInt(String.valueOf(orderTaskMap.get("ispo")));

        //判断该项目是否是首次推广，主要解决计件任务多个合同问题
        if(101001 == ispo){
            //查询推广费支付百分比值，7为固定配置表ID
            proExpensesPer = commonPayService.findScaleValue(7);
        }


        //计算手续费和推广费
        float total_price = Float.parseFloat(String.valueOf(map.get("total_price")));

        float fee = total_price * feePer / 100;
        float popur = total_price * proExpensesPer / 100;


        //放入推广费
        orderTaskMap.put("popur",popur);
        orderTaskMap.put("fee",fee);

        taskSigningDao.updateOrderTaskById(orderTaskMap);



        //新增项目订单表数据
        Map orderItem = new HashMap();

        //查询艺术家推荐者
        String presenter = taskSigningDao.findPresenterByUserId(String.valueOf(map.get("artist_userId")));

        //如果推荐人ID为空那么就赋值为-1
        if(presenter == null || "".equals(presenter)){
            presenter = "-1";
        }


        orderItem.put("order_task_id",orderTaskMap.get("order_task_id"));
        orderItem.put("item_id",map.get("item_id"));
        orderItem.put("total_price",total_price);
        orderItem.put("fee",fee);
        orderItem.put("popur",popur);
        orderItem.put("presenter",presenter);
        orderItem.put("baile_id",map.get("baile_id"));
        orderItem.put("artist_id",map.get("artist_id"));
        orderItem.put("item_contract_id",contractId);

        //插入项目订单表
        taskSigningDao.insertOrderItem(orderItem);

        //查询阶段数据
        List<Map<String,Object>> ItemStageList = taskSigningDao.findItemStageByContractId(contractId);

        //推广费
        Map orderPopurMap = new HashMap();
        //手续费
        Map orderFeeMap = new HashMap();
        //订单阶段明细
        Map orderStageMap = new HashMap();
        //四舍五入保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");

        for(Map itemStage : ItemStageList){

            //阶段支付金额比例
            float scale = Float.parseFloat(String.valueOf(itemStage.get("scale")));

            float popurF = Float.parseFloat(df.format(total_price * scale / 100 * proExpensesPer / 100));
            float feeF = Float.parseFloat(df.format(total_price * scale / 100 * feePer / 100));
            float stageF = Float.parseFloat(df.format(total_price * scale / 100 - popurF - feeF));

            orderPopurMap.put("order_task_id",orderTaskMap.get("order_task_id"));
            orderPopurMap.put("stage_id", itemStage.get("stage_id"));
            orderPopurMap.put("price", popurF );//应付阶段手续费
            orderPopurMap.put("item_contract_id",contractId);

            orderFeeMap.put("item_order_id",orderItem.get("item_order_id"));
            orderFeeMap.put("stage_id",itemStage.get("stage_id"));
            orderFeeMap.put("price", feeF);//应付阶段手续费

            orderStageMap.put("item_order_id",orderItem.get("item_order_id"));
            orderStageMap.put("stage_id",itemStage.get("stage_id"));
            orderStageMap.put("price", stageF);//应付阶段费用

            taskSigningDao.insertOrderPopur(orderPopurMap);
            taskSigningDao.insertOrderFee(orderFeeMap);
            taskSigningDao.insertOrderStage(orderStageMap);

            //判断第一阶段预存资金够不够，够就开启第一阶段
            if("125101".equals(String.valueOf(itemStage.get("stage")))){

                //得到项目剩余预存资金
                float prestoreSurplus = taskSigningDao.findOrderTaskPrestoreSurplus(String.valueOf(orderTaskMap.get("order_task_id")));
                //阶段总费用
                float stageSumMoney = popurF + feeF + stageF;

                //如果预存资金足够，那么就开启第一阶段,并减去阶段总费用
                if(prestoreSurplus >= stageSumMoney){

                    //改变状态为进行中
                    orderStageMap.put("stage_status",134003);

                    taskSigningDao.updateItemStageStatusById(orderStageMap);

                    orderPopurMap.put("stageSumMoney",stageSumMoney);
                    taskSigningDao.updateOrderTaskPrestoreSurplus(orderPopurMap);

                }else{
                    //改变状态为预存资金
                    orderStageMap.put("stage_status",134002);

                    taskSigningDao.updateItemStageStatusById(orderStageMap);

                }


            }

        }

        //判断已确认计件数量是否等于任务总计件数量，如果是就维护项目流程
        //判断是否是计件任务
        if(101001 == Integer.parseInt(String.valueOf(map.get("is_piece")))){

            //得到确认计件数量
            int surePieceNum = taskSigningDao.findSumSurePieceNum(String.valueOf(map.get("item_id")));
            //得到总计件数
            int sumPieceNum = taskSigningDao.findSumPieceNum(String.valueOf(map.get("item_id")));

            //如果相等，表示这个任务已结束
            if(sumPieceNum == surePieceNum){
                //改变当前任务进度
                taskSigningDao.updateCurrentProgressByTaskId(String.valueOf(map.get("item_id")));
            }
        }else{
            //改变当前任务进度
            taskSigningDao.updateCurrentProgressByTaskId(String.valueOf(map.get("item_id")));
        }

    }

}
